package tree.迭代bfs.剑指;

import po.TreeNode;

import java.util.*;

/**
 * @author songZiHao
 * @version 1.0.0
 * @ClassName 剑指Offer从上到下打印二叉树III32.java
 * @Description TODO
 * @createTime 2021年03月28日 11:15:00
 */
public class 剑指Offer从上到下打印二叉树III32 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> lists = new ArrayList<>();
        if (root == null) {
            return lists;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int num = 1;
        while (!queue.isEmpty()) {
            int size = queue.size();
            Deque<Integer> integers = new LinkedList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (num % 2 == 0) {
                    integers.offerFirst(node.val);
                } else {
                    integers.offerLast(node.val);
                }
                if (node.left!=null){
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            num += 1;
            lists.add(new ArrayList<>(integers));
        }
        return lists;
    }
}
